import 'package:flutter/services.dart';
import 'package:flutter_plugin_sdk_storekit/channel/storekit_channel.dart'; // 添加这一行以导入 MethodCall 类

class StoreKitChannelPlugin {
  static final StoreKitChannelPlugin _instance = StoreKitChannelPlugin._internal();
  final MethodChannel _subscribeChannel = const MethodChannel(StoreKitChannel.subscribeChannel); //订阅通道

  factory StoreKitChannelPlugin() {
    return _instance;
  }

  StoreKitChannelPlugin._internal() {
    // // 在实例化时立即设置方法处理器
    // setupMethodHandlers();
  }

  // 存储用户配置的回调
  StoreKitCallback? _callback;

  // 配置插件
  void configure({
    required StoreKitCallback callback,
  }) {
    _callback = callback;
    // 在实例化时立即设置方法处理器
    setupMethodHandlers();
  }

  //订阅通道方法
  // 设置方法处理器
  void setupMethodHandlers() {
    _subscribeChannel.setMethodCallHandler(_handleSubscriptionMethods);
  }

  // 处理从iOS发来的方法调用
  Future<void> _handleSubscriptionMethods(MethodCall call) async {
    switch (call.method) {
      case 'onProductsReceived':
        //接收订阅产品
        final List<dynamic> rawProducts = call.arguments['products'];
        final List<Map<String, dynamic>> products = rawProducts.map((item) => Map<String, dynamic>.from(item)).toList();
        _callback?.onProductsReceived(products);
        break;
      case 'onSubscribedReceived':
        //接收订阅
        _callback?.onSubscriptionUpdated(
          call.arguments['isSubscribed'],
          Map<String, dynamic>.from(call.arguments['orderData']),
          Map<String, dynamic>.from(call.arguments['reportRequestData']),
          Map<String, dynamic>.from(call.arguments['product']),
        );
        break;
      case 'getSubscriptionHistoryOrder':
        //获取订阅的历史订单
        final List<dynamic> rawHistoryOrder = call.arguments['historyTransaction'];
        final List<Map<String, dynamic>> historyOrder =
            rawHistoryOrder.map((item) => Map<String, dynamic>.from(item)).toList();
        _callback?.getSubscriptionHistoryOrder(historyOrder);
        break;
      case 'noSubscription':
        //没有订阅（针对15.0以上是准确的）
        _callback?.onNoSubscriptionUpdated();
        break;
      default:
    }
  }

  //获取订阅产品列表
  /*
     baseURL: String 默认值："https://pst.irsubs.com"
     checkOrder: String //IAP支付订单验证接口 默认值："/tlsun/iap/check-order"
     report: String //IAP订单上报接口 默认值："/tlsun/report/iap"
     productIds: [String] //产品的id
     ssAccountId: String? //数数接入的账号id
     ssDistinctId: String? //数数接入的访客id
     language: String? //设置语音
     retryTime: Double//设置重试时间，默认是1.0s
  */
  Future<List<Map<String, dynamic>>> getSubscriptionProductList(
      {required List<String> productIds,
      String? ssAccountId,
      String? ssDistinctId,
      required String language,
      String? baseURL,
      String? checkOrder,
      String? report,
      double? retryTime}) async {
    final result = await _subscribeChannel.invokeMethod(StoreKitChannel.getSubscriptionProductList, {
      "productIds": productIds,
      "ssAccountId": ssAccountId,
      "ssDistinctId": ssDistinctId,
      "language": language,
      "baseURL": baseURL,
      "checkOrder": checkOrder,
      "report": report,
      "retryTime": retryTime,
    });
    // 安全的类型转换
    if (result is List) {
      return result.map((item) {
        if (item is Map) {
          return Map<String, dynamic>.from(item.map((key, value) => MapEntry(key.toString(), value)));
        }
        return <String, dynamic>{};
      }).toList();
    }
    return [];
  }

  //购买订阅
  Future<(bool, String)> purchaseSubscription(String productId, Map<String, dynamic> reportDic) async {
    final result = await _subscribeChannel
        .invokeMethod(StoreKitChannel.purchaseSubscription, {"productId": productId, "reportDic": reportDic});
    if (result is List && result.length >= 2) {
      return (result[0] as bool, result[1] as String);
    }
    // 默认返回错误情况
    return (false, "返回数据格式错误");
  }

  //恢复订阅
  Future<(bool, String)> restoreSubscription() async {
    final result = await _subscribeChannel.invokeMethod(StoreKitChannel.restoreSubscribe);
    if (result is List && result.length >= 2) {
      return (result[0] as bool, result[1] as String);
    }
    // 默认返回错误情况
    return (false, "返回数据格式错误");
  }

  //上报订阅
  Future<bool> reportIapSubscription(String productId) async {
    final result =
        await _subscribeChannel.invokeMethod(StoreKitChannel.reportIapSubscription, {"productId": productId});
    return result;
  }
}

// 回调接口，供应用实现
abstract class StoreKitCallback {
  void onProductsReceived(List<Map<String, dynamic>> products);
  void onSubscriptionUpdated(bool isSubscribed, Map<String, dynamic> orderData, Map<String, dynamic> reportRequestData,
      Map<String, dynamic> product); //有订阅的回掉
  void onNoSubscriptionUpdated(); //没有订阅的回掉(针对15.0以上是准确的）
  void getSubscriptionHistoryOrder(List<Map<String, dynamic>> orderData); //获取订阅的历史订单
}
